package com.inno.sms.utils;



import com.alibaba.fastjson.JSON;
import com.aliyun.auth.credentials.Credential;
import com.aliyun.auth.credentials.provider.StaticCredentialProvider;
import com.aliyun.sdk.service.dysmsapi20170525.AsyncClient;
import com.aliyun.sdk.service.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.sdk.service.dysmsapi20170525.models.SendSmsResponse;
import com.inno.sms.error.SmsException;
import darabonba.core.client.ClientOverrideConfiguration;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CompletableFuture;

@Slf4j
@Component
public class SmsUtil {

    private static String signName;

    @Value("${sms.aliyun.signName}")
    public void setSignName(String signName) {
        SmsUtil.signName = signName;
    }

    private static String CodeTemplateCode;

    @Value("${sms.aliyun.CodeTemplateCode}")
    public void setTemplateCode(String templateCode) {
        SmsUtil.CodeTemplateCode = templateCode;
    }

    private static String accessKeyId;

    @Value("${sms.aliyun.accessKeyId}")
    public void setAccessKeyId(String accessKeyId) {
        SmsUtil.accessKeyId = accessKeyId;
    }

    private static String accessKeySecret;

    @Value("${sms.aliyun.accessKeySecret}")
    public void setAccessKeySecret(String accessKeySecret) {
        SmsUtil.accessKeySecret = accessKeySecret;
    }


    /**
     * 发送验证码
     * 短信示例：【阿里云短信测试】您正在使用阿里云短信测试服务，体验验证码是：564655，如非本人操作，请忽略本短信！
     * 官方示例代码：https://next.api.aliyun.com/api/Dysmsapi/2017-05-25/SendSms?spm=api-workbench.API%20Document.0.0.5be349a5NCOHvS&tab=DEMO
     *
     * @param mobile
     * @param code
     * @return
     */
    public static SendSmsResponse sendCode(String mobile, String code) {
        log.info("发送验证码手机号：{}，验证码：{}，签名：{}，模板：{}", mobile, code, signName, CodeTemplateCode);
        Map<String, String> map = new HashMap<>();
        map.put("code", code);
        StaticCredentialProvider provider = StaticCredentialProvider.create(Credential.builder()
                .accessKeyId(accessKeyId)
                .accessKeySecret(accessKeySecret)
                .build());
        AsyncClient client = AsyncClient.builder()
                .region("cn-shanghai")
                .credentialsProvider(provider)
                .overrideConfiguration(ClientOverrideConfiguration.create().setEndpointOverride("dysmsapi.aliyuncs.com"))
                .build();
        SendSmsResponse resp = null;

        try {
            SendSmsRequest sendSmsRequest = SendSmsRequest.builder().signName(signName)
                    .templateCode(CodeTemplateCode)
                    .phoneNumbers(mobile)
                    .templateParam(JSON.toJSONString(map))
                    .build();

            CompletableFuture<SendSmsResponse> response = client.sendSms(sendSmsRequest);

            resp = response.get();
            log.info("短信发送结果：{}", JSON.toJSONString(resp));
            if (!"OK".equals(resp.getBody().getCode()) && !"isv.SMS_TEST_NUMBER_LIMIT".equals(resp.getBody().getCode())) {
                throw new SmsException("发送短信失败！");
            }
        } catch (Exception e) {
            log.error("发短信异常", e);
            throw new SmsException("发送短信失败");
        } finally {
            client.close();
        }
        return resp;
    }


}